import { Component, ViewEncapsulation } from '@angular/core';
import { FormBuilder, FormGroup, Validator, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { Observable } from 'rxjs/Rx';

import { LoginService } from '../Login.service';
import { phoneNumberValidator } from 'utils/index';

import { setLocalItem, removeItem, getLocalItem } from 'utils';

@Component({
    selector: 'login',
    encapsulation: ViewEncapsulation.Emulated,
    templateUrl: './Login.html',
    styleUrls: []
  }
)

export class LoginComponent {

  public loginForm:FormGroup;

  //loading
  private loading: boolean = false;
  //后端错误
  private error: string = null;

  // 记住用户localStorage
  private yskjAccount: any = getLocalItem('yskjAccount');

  constructor(private formBuilder:FormBuilder, private router: Router,private route: ActivatedRoute, private loginService:LoginService, private title:Title) {
  }

  ngOnInit() {
    this.title.setTitle("登录");
    this.loginForm = this.formBuilder.group({
      grant_type: ['password'],
      scope: ['Login:PhoneNumber'],
      username: [ this.yskjAccount ? this.yskjAccount.username : '', Validators.compose([Validators.required, phoneNumberValidator])], // 17681864100
      password: [ this.yskjAccount ? this.yskjAccount.password : '', Validators.compose([Validators.required])], // 111111
      remember: [ this.yskjAccount ? true : false ],
    });
    this.route.params.subscribe(data => {
      const auth = data["auth"];
      if(auth === 'unauth'){
        this.error = '请先登录';
      }
    });
  }

  // 清除输入框内容
  clear(key) {
    const value = this.loginForm.value;
    value[key] = '';
    this.loginForm.setValue(value);
  }

  // 登录
  login(form) {
    if (form.valid) {
      // 记住用户
      if (form.value.remember) {
        const yskjAccount = {
          username: form.value.username,
          password: form.value.password
        };
        setLocalItem("yskjAccount", yskjAccount);
      } else {
        removeItem('yskjAccount');
      }

      // 访问登录接口，存储返回数据
      this.loading = true;
      this.loginService.loginIn(form.value).then((data) => {
        this.loading = false;
        this.error = null;
        if (data) {
          this.loginService.emit.emit(true);
          setLocalItem("auth", data);
          // if (document.referrer === '') {
          //   this.router.navigate(['/index']);
          // } else {
          //   window.history.back();
          // }
          this.router.navigate(['/index']);
        } else {
          removeItem('auth');
        }
      }).catch((e) => {
        this.loading = false;
        if(e.status === 400) {
          this.error = '用户名或密码错误';
          removeItem('auth');
        }
        return Observable.throw(e);
      });
    }
  }

}
